﻿using System;
using System.Net;
using System.ServiceModel.Channels;
using Microsoft.ServiceBus;
using SimpleServiceBus.Bus;
using SimpleServiceBus.Endpoints.DotNetServiceBus.Utilities;

namespace SimpleServiceBus.Endpoints.DotNetServiceBus.Transport
{
 
    public class DotNetServiceBusQueueTransport : DotNetServiceBusTransportBase
    {
        private AzureQueueManager _inputQueue;
        private Uri _queueUri;


        public string InputQueueName { get; set; }
        public string PoisonQueueName { get; set; }

        public DotNetServiceBusQueueTransport()
        {
            InputQueueName = Dns.GetHostName();
            PoisonQueueName = InputQueueName + "_Poison";
            ReceiveTimeOut = TimeSpan.FromSeconds(30);
            SendTimeOut = TimeSpan.FromSeconds(30);
        }

        public override string ReturnAddress
        {
            get
            {
                return QueueUri.ToString();
            }

        }

        public Uri QueueUri
        {
            get
            {
                if (_queueUri == null)
                {
                    _queueUri = ServiceBusEnvironment.CreateServiceUri("sb", BusSolutionName, "/" + InputQueueName + "/");
                    
                }
                return _queueUri;
            }
            set { _queueUri = value; }
        }


        public override int GetNumberOfPendingMessages()
        {
            return -1;
        }

        protected override MessageEnvelope GetNextMessage()
        {
            MessageEnvelope envelope;
            Message message = null;
            try
            {
                message = _inputQueue.Queue.PeekLock(ReceiveTimeOut);
                envelope = CreateMessageEnvelopeFromWcfMessage(message);
            }
            catch (Exception)
            {
                if (message != null)
                    _inputQueue.Queue.ReleaseLock(message);
                throw;
            }
            _inputQueue.Queue.DeleteLockedMessage(message);
            return envelope;
        }

        protected override void StartService()
        {
            BindToInputQueue();
            base.StartService();
        }

        protected override void ShutDownService()
        {
            if (_inputQueue != null)
                _inputQueue.Dispose();
            base.ShutDownService();
        }

        protected void BindToInputQueue()
        {
            _inputQueue = new AzureQueueManager(QueueUri,BusSolutionName,BusSolutionPassword);
        }
    }
}
